import { STORE_KEYS } from '@/configs/store.config';
import { Person } from '@/types/persons';
import { useLocalStorageState } from 'ahooks';
import { useCallback, useMemo } from 'react';

export function usePersonsStore() {
  const [persons, setPersons] = useLocalStorageState<Person[]>(
    STORE_KEYS.PERSONS_STORE,
    {
      defaultValue: [],
    },
  );

  const showPersons = useMemo(
    () => persons.filter(showPerson => !showPerson.archived),
    [persons],
  );

  function addPerson(person: Person) {
    setPersons([...persons, person]);
  }

  function removePerson(person: Person) {
    person.archived = true;
    setPersons([...persons]);
  }

  function mutatePerson(person: Person) {
    const target = persons.find(p => p.id === person.id);
    if (target) {
      Object.assign(target, person);
      setPersons([...persons]);
    }
  }

  const getPersonById = useCallback(
    function (id: string | undefined) {
      if (!id) return undefined;
      return persons.find(p => p.id === id);
    },
    [persons],
  );

  const getPersonsByIds = useCallback(
    (ids: (string | undefined)[]) => ids.map(getPersonById),
    [getPersonById],
  );

  return {
    showPersons,
    addPerson,
    removePerson,
    mutatePerson,
    getPersonById,
    getPersonsByIds,
  };
}
